<template>
    <div class="manage">
        <el-dialog :title="modalType == 0 ? '新增' : '编辑'" :visible.sync="dialogVisible" width="50%"
            :before-close="handleClose">
            <!-- 表单信息 -->
            <el-form ref="form" :rules="rules" :inline="true" :model="form" label-width="80px" size="mini">
                <el-form-item label="昵称" prop="nickname">
                    <el-input clearable placeholder="请输入姓名" v-model="form.nickname"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-select v-model="form.gender" placeholder="请选择">
                        <el-option label="男" value="男"></el-option>
                        <el-option label="女" value="女"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="图片" prop="details">
                    <el-upload class="upload-demo" action="" accept="image/*" :limit="1" :on-exceed="handleExceed"
                        :http-request="handleUpload" :before-upload="beforeUpload" list-type="picture-card"
                        :on-remove="handleRemove" :fileList="fileList">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel" size="mini">取消</el-button>
                <el-button type="primary" @click="submit" size="mini">确 定</el-button>
            </span>
        </el-dialog>
        <div class="manage-header">
            <!-- 搜索表单 -->
            <el-form :inline="true" :model="search">
                <el-form-item>
                    <el-input clearable size="mini" placeholder="用户名或昵称" v-model="search.content"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="mini" @click="getList">查询</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="common-tabel">
            <el-table stripe height="100%" border :data="tableData" style="width: 100%" v-loading="loading" size="mini">
                <el-table-column prop="username" label="用户名" align="center">
                </el-table-column>
                <el-table-column prop="nickname" label="昵称" align="center">
                </el-table-column>
                <el-table-column prop="gender" label="性别" align="center">
                </el-table-column>
                <el-table-column prop="avatar" label="头像" align="center">
                    <template slot-scope="scope">
                        <img :src="global.URL + scope.row.avatar" width="60px" height="60px" alt="">
                    </template>
                </el-table-column>
                <el-table-column prop="created" label="注册时间" align="center">
                </el-table-column>
                <el-table-column prop="action" label="操作" align="center" width="150px">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>
<script>
import { userList, userEdit, userDelete } from '@/api/user.js';
import { upload } from '@/api/upload.js';
export default {
    data() {
        return {
            dialogVisible: false,
            form: {
                nickname: '',
                gender: '',
            },
            rules: {
                nickname: [
                    { required: true, message: '请输入姓名' }
                ],
                gender: [
                    { required: true, message: '请选择性别' }
                ],
            },
            tableData: [],
            modalType: 0, // 0表示新增的弹窗， 1表示编辑
            search: {
                content: '',
            },
            loading: false,
            fileList: []
        }
    },
    methods: {
        handleExceed() {
            this.$message.warning('只能上传一张照片');
        },
        beforeUpload(file) {
            if (!file.type.startsWith('image')) {
                this.$message.warning('请上传图片');
                return false
            };
        },
        handleUpload(file) {
            let formData = new FormData();
            formData.append("file", file.file);
            upload(formData).then(({ result }) => {
                this.fileList.push({ url: this.global.URL + result.url })
            });
        },
        handleRemove(file) {
            this.fileList = this.fileList.filter(function (item) {
                return item.url !== file.url;
            });
        },
        // 提交表单
        submit() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let urls = this.fileList.map(function (item) {
                        let url = item.url;
                        let startIndex = url.indexOf('/public/images/');
                        if (startIndex !== -1) {
                            return url.substring(startIndex);
                        } else {
                            return null;
                        }
                    });
                    // 过滤掉值为 null 的项（可选，视情况而定）
                    urls = urls.filter(function (item) {
                        return item !== null;
                    });

                    // 使用 join() 方法将提取的 url 属性值用逗号分隔拼接成字符串
                    let temp = urls.join(',');
                    this.form.avatar = temp;
                    let api = userEdit;
                    api(this.form).then(({ code }) => {
                        if (code == 0) {
                            // 清空表单数据
                            this.$refs.form.resetFields()
                            // 关闭弹窗
                            this.dialogVisible = false
                            // 重新获取列表接口
                            this.getList()
                        };
                    })
                }
            })
        },
        // 弹窗关闭
        handleClose() {
            this.$refs.form.resetFields()
            this.dialogVisible = false
        },
        cancel() {
            this.handleClose()
        },
        // 编辑
        handleEdit(row) {
            this.modalType = 1
            this.dialogVisible = true
            this.form = JSON.parse(JSON.stringify(row))
            let that = this;
            let pictureArray = row.avatar.split(',');
            this.fileList = pictureArray.map(function (picturePath) {
                return { url: that.global.URL + picturePath };
            });
        },
        // 删除
        handleDelete(row) {
            this.$confirm('确定删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                userDelete({ id: row.id }).then(() => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getList()
                })

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 获取列表数据
        getList() {
            this.loading = true;
            userList({ content: this.search.content }).then((data) => {
                this.tableData = data.result
                this.loading = false;
            })
        },
    },
    mounted() {
        this.getList()
    }
}
</script>
<style lang="less" scoped>
.manage {

    height: 100%;

    .manage-header {
        display: flex;
        justify-content: end;
        align-items: center;
        margin-bottom: 10px;

        .el-form-item {
            margin-bottom: 0;
        }

        /deep/.el-form-item__content {
            line-height: 0;
        }
    }

    .common-tabel {
        position: relative;
        height: calc(100% - 62px);
    }
}
</style>